import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:get/get.dart';
import 'package:mziot/app/config/design.dart';
import 'package:mziot/app/data/device_list_entity.dart';
import 'package:mziot/app/modules/devices/add_device/controllers/add_device_controller.dart';
import 'package:mziot/app/modules/devices/device_provider.dart';
import 'package:mziot/app/tools/blue_service.dart';
import 'package:mziot/app/tools/tools.dart';
import 'package:mziot/generated/locales.g.dart';

class WifiController extends GetxController {
  DeviceProvider provider = DeviceProvider();
  TextEditingController nameController = TextEditingController();
  TextEditingController passController = TextEditingController();
  DiscoveredDevice? bluetoothDevice;
  DeviceListList? deviceInfo;
  Timer? _timer;
  final ssid = "".obs;
  final pass = "".obs;
  final isSee = false.obs;
  final isLoading = false.obs;
  int? deviceId;
  var isSend = false;

  @override
  void onInit() {
    super.onInit();

    if (Get.arguments is DiscoveredDevice) {
      bluetoothDevice = Get.arguments;
    } else if (Get.arguments is DeviceListList) {
      deviceInfo = Get.arguments;
    }
    deviceId = int.parse(Get.parameters['id'] as String);
  }

  @override
  void onReady() async {
    super.onReady();

    if (bluetoothDevice != null) {
      await BlueService.share.stopScan();
      Future.delayed(Duration(seconds: 1), () {
        if (BlueService.share.deviceState != DeviceConnectionState.connected) {
          BlueService.share.connectDevice(bluetoothDevice);
        }
      });
    }
  }

  void setDevice() async {
    FocusManager.instance.primaryFocus?.unfocus();
    final result = await MPermission.instance.bluetooth();

    if (ssid.value.isEmpty || !result) {
      return;
    }

    Future.delayed(Duration(milliseconds: 300), () {
      Get.generalDialog(pageBuilder: (ctx, a, s) {
        return CupertinoAlertDialog(
          content: Text(
            '${LocaleKeys.add_devices_wifi_name.tr}: ${ssid.value} \n ${LocaleKeys.add_devices_password.tr}: ${pass.value}',
            style: MFont.semi_Bold17.apply(color: MColor.xFF333333),
          ),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Get.back();
              },
              child: Text(
                LocaleKeys.home_no.tr,
                style: MFont.regular17.apply(color: MColor.xFF333333),
              ),
            ),
            TextButton(
              onPressed: () {
                Get.back();
                wifiConfig();
              },
              child: Text(
                LocaleKeys.home_yes.tr,
                style: MFont.semi_Bold17.apply(color: MColor.xFF333333),
              ),
            ),
          ],
        );
      });
    });
  }

  void wifiConfig() async {
    final enable = await MPermission.instance.bluetooth();
    if (!enable) {
      return;
    }
    String? deviceId;
    if (bluetoothDevice != null) {
      deviceId = bluetoothDevice?.name.split('_').last;
    } else {
      deviceId = deviceInfo?.deviceSerialnum;
    }
    if (BlueService.share.deviceState == DeviceConnectionState.disconnected &&
        bluetoothDevice != null) {
      BlueService.share.connectDevice(bluetoothDevice);
    }
    final info = BlueService.share.deviceInfo(deviceId);
    if (info?.ssid == ssid.value && info?.password == pass.value) {
      isLoading.value = false;
      showToast(LocaleKeys.tips_same_pass.tr);
      Future.delayed(Duration(seconds: 1), () {
        Get.back();
      });
      return;
    }
    if (_timer != null) {
      return;
    }

    fetchAddWifi();
  }

  void timerStop() {
    _timer?.cancel();
    _timer = null;
    isLoading.value = false;
    EasyLoading.dismiss();
  }

  void fetchAddWifi() async {
    if (isLoading.value) {
      return;
    }
    isLoading.value = true;
    EasyLoading.show();
    provider.addWifi(ssid.value, pass.value, deviceId ?? 0).then((value) async {
      if (value.isSuccess) {
        var count = 0;
        String? deviceId;
        if (bluetoothDevice != null) {
          deviceId = bluetoothDevice?.name.split('_').last;
        } else {
          deviceId = deviceInfo?.deviceSerialnum;
        }
        if (!isSend && BlueService.share.writeCharacteristic != null) {
          isSend = true;
          BlueService.share.execCmds(value.data);
        }
        _timer = Timer.periodic(Duration(seconds: 4), (_) async {
          if (BlueService.share.deviceState == DeviceConnectionState.disconnected &&
              bluetoothDevice != null) {
            BlueService.share.connectDevice(bluetoothDevice);
          }
          if (!isSend && BlueService.share.writeCharacteristic != null) {
            isSend = true;
            BlueService.share.execCmds(value.data);
          }
          count++;
          if (count == 10) {
            showToast(LocaleKeys.tips_time_out.tr);
            timerStop();
            isSend = false;
            return;
          }

          final info = BlueService.share.deviceInfo(deviceId);
          final isWifi = info?.isWifi ?? 0;
          if (info?.ssid == ssid.value && info?.password == pass.value && isWifi == 1) {
            timerStop();
            Future.delayed(Duration(seconds: 1), () {
              Get.back();
            });
          }
        });
      } else {
        EasyLoading.dismiss();
        showToast(value.msg ?? '');
      }
    }).catchError((_) {
      EasyLoading.dismiss();
    });
  }

  @override
  void onClose() async {
    nameController.dispose();
    passController.dispose();
    _timer?.cancel();
    EasyLoading.dismiss();
    if (bluetoothDevice != null) {
      BlueService.share.isAll = true;
      Get.find<AddDeviceController>().scanDevices('MZ_MZ');
    }
  }
}
